package com.wannengbang.cloudleader.service;

import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseActivity;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.BankListBean;
import com.wannengbang.cloudleader.bean.BaseResponseBean;
import com.wannengbang.cloudleader.bean.CardListBean;
import com.wannengbang.cloudleader.dialog.ChooseBankDialog;
import com.wannengbang.cloudleader.event.CardEvent;
import com.wannengbang.cloudleader.service.model.IServiceModel;
import com.wannengbang.cloudleader.service.model.ServiceModelImpl;
import com.wannengbang.cloudleader.utils.DateTimeUtil;
import com.wannengbang.cloudleader.utils.NumberFormatUtils;
import com.wannengbang.cloudleader.utils.ToastUtil;
import com.wannengbang.cloudleader.widget.AppTitleBar;
import com.wannengbang.cloudleader.widget.ViewLoading;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AddCardActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.edit_no)
    EditText editNo;
    @BindView(R.id.edit_limit)
    EditText editLimit;
    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.ll_bank_name)
    LinearLayout llBankName;
    @BindView(R.id.tv_due_day)
    TextView tvDueDay;
    @BindView(R.id.ll_due_day)
    LinearLayout llDueDay;
    @BindView(R.id.tv_bill_day)
    TextView tvBillDay;
    @BindView(R.id.ll_bill_day)
    LinearLayout llBillDay;
    @BindView(R.id.tv_expiry_date)
    TextView tvExpiryDate;
    @BindView(R.id.ll_expiry_date)
    LinearLayout llExpiryDate;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    private IServiceModel serviceModel;
    private ArrayList<String> options1Items = new ArrayList<>();
    private Calendar selectedDate;
    private String bank_id = "";
    private CardListBean.DataBean.ItemListBean dataBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_card);
        ButterKnife.bind(this);
        initView();
        requestBankList();
    }

    public void initView() {
        dataBean = (CardListBean.DataBean.ItemListBean) getIntent().getSerializableExtra("DataBean");
        selectedDate = Calendar.getInstance();
        serviceModel = new ServiceModelImpl();
        for (int i = 1; i <= 31; i++) {
            options1Items.add(i + "");
        }

        if (dataBean != null) {
            editName.setText(dataBean.getReal_name());
            if (!TextUtils.isEmpty(dataBean.getReal_name())) {
                editName.setSelection(dataBean.getReal_name().length());
            }
            editNo.setText(dataBean.getNo());
            if (!TextUtils.isEmpty(dataBean.getNo())) {
                editNo.setSelection(dataBean.getNo().length());
            }
            String limit = NumberFormatUtils.formatDouble(Double.parseDouble(dataBean.getLimit()) / 100);
            editLimit.setText(limit);
            if (!TextUtils.isEmpty(limit)) {
                editLimit.setSelection(limit.length());
            }

            tvBankName.setText(dataBean.getBank_name());
            bank_id = dataBean.getBank_id();

            tvDueDay.setText(dataBean.getDue_day());
            tvBillDay.setText(dataBean.getBill_day());
            tvExpiryDate.setText(dataBean.getExpiry_date());


        }
    }

    public void requestBankList() {
        serviceModel.requestBankList(new DataCallBack<BankListBean>() {
            @Override
            public void onSuccessful(BankListBean bean) {

            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestCardAdd(String no, String real_name, String bank_id, String due_day, String bill_day, String limit, String expiry_date) {
        serviceModel.requestCardAdd(no, real_name, bank_id, due_day, bill_day, limit, expiry_date, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort("添加成功");
                EventBus.getDefault().post(new CardEvent());
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestCardEdit(String id, String no, String real_name, String bank_id, String due_day, String bill_day, String limit, String expiry_date) {
        serviceModel.requestCardEdit(id, no, real_name, bank_id, due_day, bill_day, limit, expiry_date, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort("修改成功");
                EventBus.getDefault().post(new CardEvent());
                finish();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private void showPickerView(String type) {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1);
                if ("due_day".equals(type)) {
                    tvDueDay.setText(tx);
                }

                if ("bill_day".equals(type)) {
                    tvBillDay.setText(tx);
                }

            }
        }).setTitleText("")
                .setTitleSize(16)
                .setSubmitColor(getResources().getColor(R.color.text_color_2))//确定按钮文字颜色
                .setSubCalSize(16)
                .setCancelColor(getResources().getColor(R.color.text_color_2))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.white))
                .setDividerColor(getResources().getColor(R.color.line_color_gray))
                .setTextColorCenter(getResources().getColor(R.color.text_color_2))
                .setContentTextSize(18)
                .setLabels("", "", "")
                .setLineSpacingMultiplier(2)
                .isDialog(true)
                .build();

        pvOptions.setPicker(options1Items);//三级选择器

        Dialog mDialog = pvOptions.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvOptions.getDialogContainerLayout().setLayoutParams(params);

            Window window = mDialog.getWindow();
            if (window != null) {
                window.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                lp.gravity = Gravity.BOTTOM;
            }
        }
        pvOptions.show();
    }

    private TimePickerView pvTime;

    public void selectTime() {
        //这里可以更改参数，有好多类型
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        startDate.set(1900, 0, 1);
        endDate.set(2099, 11, 31);
        pvTime = new TimePickerBuilder(mActivity, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String param = DateTimeUtil.format23(date);
                tvExpiryDate.setText(param);
            }
        }).setType(new boolean[]{true, true, false, false, false, false})
                .setSubmitColor(getResources().getColor(R.color.text_color_2))//确定按钮文字颜色
                .setSubCalSize(14)
                .setCancelColor(getResources().getColor(R.color.text_color_2))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.white))
                .setDividerColor(getResources().getColor(R.color.line_color_gray))
                .setTextColorCenter(getResources().getColor(R.color.text_color_2))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2)
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window window = mDialog.getWindow();
            if (window != null) {
                window.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                lp.gravity = Gravity.BOTTOM;
            }
        }
        pvTime.show();
    }


    @OnClick({R.id.ll_bank_name, R.id.ll_due_day, R.id.ll_bill_day, R.id.ll_expiry_date, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_bank_name:
                ChooseBankDialog dialog = ChooseBankDialog.newInstance();
                dialog.show(getSupportFragmentManager(), "dialog");
                dialog.setOnCallBackListener((name, chooseId) -> {
                    tvBankName.setText(name);
                    bank_id = chooseId;
                });
                break;
            case R.id.ll_due_day:
                showPickerView("due_day");
                break;
            case R.id.ll_bill_day:
                showPickerView("bill_day");
                break;
            case R.id.ll_expiry_date:
                selectTime();
                break;
            case R.id.tv_commit:

                String real_name = editName.getText().toString();
                if (TextUtils.isEmpty(real_name)) {
                    ToastUtil.showShort("请输入开户名");
                    return;
                }
                String no = editNo.getText().toString();
                if (TextUtils.isEmpty(no)) {
                    ToastUtil.showShort("请输入信用卡卡号");
                    return;
                }
                String limit = editLimit.getText().toString();
                if (TextUtils.isEmpty(limit)) {
                    ToastUtil.showShort("请输入信用卡额度");
                    return;
                }

                if (TextUtils.isEmpty(bank_id)) {
                    ToastUtil.showShort("请选择银行名称");
                    return;
                }

                String due_day = tvDueDay.getText().toString();
                if (TextUtils.isEmpty(due_day)) {
                    ToastUtil.showShort("请选择还款日");
                    return;
                }
                String bill_day = tvBillDay.getText().toString();
                if (TextUtils.isEmpty(bill_day)) {
                    ToastUtil.showShort("请选择账单日");
                    return;
                }

                String expiry_date = tvExpiryDate.getText().toString();
                if (TextUtils.isEmpty(expiry_date)) {
                    ToastUtil.showShort("请选择信用卡有效期");
                    return;
                }
                ViewLoading.showProgress(mActivity, "提交中......");
                String limit1 = NumberFormatUtils.formatDouble(Double.parseDouble(limit) * 100);
                if (dataBean != null) {
                    requestCardEdit(dataBean.getId(), no, real_name, bank_id, due_day, bill_day, limit1, expiry_date);
                } else {
                    requestCardAdd(no, real_name, bank_id, due_day, bill_day, limit1, expiry_date);
                }
                break;
        }
    }
}
